<?php
declare (strict_types=1);

namespace app\common\model;

use think\Collection;
use Exception;

class Menu extends CommonBase
{

    public function getAllMenu(array $where = []): Collection
    {
        $where['is_delete'] = config('status.mysql.table_normal');
        return $this->where($where)->order('sort asc')->select();
    }

    public function getMenuList(int $page = 1, int $limit = 10, array $where = []): Collection
    {
        $where['is_delete'] = config('status.mysql.table_normal');
        $offset             = ($page - 1) * $limit;
        return $this->where($where)->limit($offset, $limit)->select();
    }

    public function getMenuCount(array $where = []): int
    {
        $where['is_delete'] = config('status.mysql.table_normal');
        return $this->where($where)->count();
    }

    public function findMenuById(int $id)
    {
        return $this->where(['id' => $id, 'is_delete' => config('status.mysql.table_normal')])->find();
    }

    public function addMenu(array $data): bool
    {
        $data['is_delete'] = config('status.mysql.table_normal');
        return (boolean)$this->save($data);
    }

    public function updateMenu(int $id, array $data): bool
    {
        $data['updated_at'] = date('Y-m-d H:i:s');
        return (boolean)$this->where(['id' => $id])->save($data);
    }

    public function deleteMenu(int $id): bool
    {
        return (boolean)$this->where(['id' => $id])->save(['is_delete' => config('status.mysql.table_delete')]);
    }

    public function findMenuByPid(int $pid)
    {
        return $this->where(['pid' => $pid, 'is_delete' => config('status.mysql.table_normal')])->select();
    }

    /**
     * @throws Exception
     */
    public function batchMenuSort(array $data): bool
    {
        try {
            $this->startTrans();
            foreach ($data as $id => $sort) {
                $this->where('id', $id)->update(['sort' => $sort]);
            }

            $this->commit();
            // Cache::delete(sprintf(self::_CACHE_KEY, $this->connection));
            return true;
        } catch (Exception $e) {
            $this->rollback();
            throw new Exception($e->getMessage());
        }
    }
}
